package com.sxt.core.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

public class ZkUtil {

	private static ZkClient zkClient = null ;

	private static final String ZK_URL = "www.yanli.ltd:2181";

	private static Map<String,List<String>> cachesServerList = new HashMap<String,List<String>>();

	static {
		zkClient = new ZkClient(ZK_URL, 4000, 10000);
	}
	/**
	 * zk注册
	 * @param serverName
	 * @param address
	 */
	public static void registerServer(String serverName,String address) {
		if(!zkClient.exists("/"+serverName)) {
			zkClient.createPersistent("/"+serverName);
		}
		if(zkClient.exists("/"+serverName+"/"+address)) {
			zkClient.delete("/"+serverName+"/"+address);
		}
		zkClient.createEphemeral("/"+serverName+"/"+address);
		System.out.println("服务："+serverName+"在"+address+"注册成功！");
	}

	public static List<String> discoverServer(String serverName){
		if(cachesServerList.containsKey(serverName)) {
			System.out.println("服务"+serverName+"在缓存列表里面有");
			return cachesServerList.get(serverName);// 也有null的时候
		}
		System.out.println("服务"+serverName+"在缓存列表里面没有");
		List<String> serverList = zkClient.getChildren("/"+serverName);
		if(serverList==null||serverList.size()==0) {
			System.out.println("服务"+serverName+"没有提供者");
			return null ;
		}
		cachesServerList.put(serverName, serverList);
       // 需要定义子节点的改变，因为要解决缓存的脏读问题
		zkClient.subscribeChildChanges("/"+serverName, new IZkChildListener() {
			
			@Override
			public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
				 System.out.println("服务"+serverName+"有服务列表上线或下线了，马上更新列表");
				 cachesServerList.put(serverName, currentChilds);
			}
		});
		return serverList;
	}
}
